package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.UUID;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

@WebServlet("/upload2")
@MultipartConfig(maxFileSize=5*1024*1024)
public class UploadServlet2 extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter pw = resp.getWriter();
		

		
		// 表单中的文本内容
		String name =req.getParameter("name");
		System.out.println(name);
		
		
		Collection<Part> parts = req.getParts();		
		for(Part part:parts)
		{
			
			if(part.getName().equals("pic"))
			{
			
			// 得到文件		
			// 文件名
			String fileName =  part.getHeader("Content-Disposition");
			System.out.println(fileName);
			int start = fileName.indexOf("filename=")+"filename=".length()+1;
			fileName = fileName.substring(start);
			fileName = fileName.substring(0, fileName.length()-1);
			System.out.println("文件名:"+fileName);
			
			// 为了避免文件名重复,产生一个随机的文件名
			// UUID
			UUID uuid = UUID.randomUUID();
			String newFileName = uuid.toString()+fileName.substring(fileName.length()-4);
			
			// 将文件保存到指定位置
			String filePath = getServletContext().getRealPath("/upload/")+newFileName;
			System.out.println(filePath);
			part.write(filePath);
			
			
			pw.println("上传的文件"+fileName+"已保存到"+filePath);
			pw.println("<img src=\"upload/"+newFileName+"\" width=\"200\" height=\"150\" /><br />");
			}
		}
		
		
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}
}
